package com.qf.springcloud.filters;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Component
public class DyRouteFilter extends ZuulFilter {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return FilterConstants.SEND_RESPONSE_FILTER_ORDER;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        // 请求参数中携带了service=consumer ,就将请求路由到Redis中存储的服务和地址中
        //1. request
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();

        //2. 去Redis查询serviceId和requestURI
        String service = request.getParameter("service");
        if ("consumer".equalsIgnoreCase(service)) {
            Map<Object, Object> map = redisTemplate.opsForHash().entries("zuul");
            String serviceId = (String) map.get("serviceId");
            String requestURI = (String) map.get("requestURI");

            //3. 将信息设置到RequestContext对象中
            requestContext.put(FilterConstants.SERVICE_ID_KEY,serviceId);
            requestContext.put(FilterConstants.REQUEST_URI_KEY,requestURI);
        }


        return null;
    }
}
